package com.huaji.learn.ui.home;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.huaji.learn.R;
import com.huaji.learn.model.NoteModel;
import com.huaji.learn.repository.NoteRepository;
import com.huaji.learn.ui.view.NoteDetailView;

public class HomeFragment extends Fragment {
    private NoteDetailView view;
    private NoteModel note;
    private NoteRepository repository;
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_home, container, false);

        repository = new NoteRepository(inflater.getContext());
        view = root.findViewById(R.id.note_detail_home);

        try {
            this.note = repository.queryNoteRandom();
            this.view.setNote(note);
        }
        catch (Exception ex){
            ex.printStackTrace();
        }

        this.view.saveButtonOnClick(v -> this.btnSaveOnClick(v));
        this.view.deleteButtonOnClick(v -> this.btnDelOnClick(v));

        return root;
    }

    void btnDelOnClick(View view) {
        if (repository.deleteNote(note.getId()) > 0) {
            Toast.makeText(view.getContext(), "删除成功", Toast.LENGTH_SHORT).show();
            try {
                this.note = repository.queryNoteRandom();
                this.view.setNote(note);
            }
            catch (Exception ex){
                Toast.makeText(view.getContext(), "删除失败", Toast.LENGTH_SHORT).show();
                ex.printStackTrace();
            }
        }
        else {
            Toast.makeText(view.getContext(), "删除失败", Toast.LENGTH_SHORT).show();
        }
    }

    void btnSaveOnClick(View view) {
        this.note = this.view.getNote();
        if (this.note.getId() < 0) {
            if (repository.insertNote(this.note) > 0) {
                Toast.makeText(view.getContext(), "新建成功", Toast.LENGTH_SHORT).show();
            }
            else {
                Toast.makeText(view.getContext(), "新建失败", Toast.LENGTH_SHORT).show();
            }
        }
        else {
            if (repository.updateNote(this.note) > 0) {
                Toast.makeText(view.getContext(), "修改成功", Toast.LENGTH_SHORT).show();
            }
            else {
                Toast.makeText(view.getContext(), "修改失败", Toast.LENGTH_SHORT).show();
            }
        }
    }
}